
#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtGui/QColor>

#include "imageLoader.h"

/*----------------------------------------------------------------------------*/


ImageLoader::ImageLoader()
{
}

/*----------------------------------------------------------------------------*/


ImageLoader::~ImageLoader()
{
	for ( size_t i = 0; i < m_imageArray.size(); i++ )
		delete m_imageArray[i];
	m_imageArray.clear();
}


/*----------------------------------------------------------------------------*/


bool ImageLoader::LoadBmpFilesToImages( const QString& _trainFilesDir )
{
	for ( size_t i = 0; i < m_imageArray.size(); i++ )
		delete m_imageArray[i];
	m_imageArray.clear();

	QStringList filesList = BrowseFiles( _trainFilesDir );

	for ( int i = 0; i < filesList.size(); i++ )
		m_imageArray.push_back( CreateImageFromBmp( filesList[i] ) );

	return ( m_imageArray.size() > 0 );
}


/*----------------------------------------------------------------------------*/


QStringList ImageLoader::BrowseFiles( const QString& _trainFilesDir )
{
	QDir currentDir = QDir::current();
	if ( !currentDir.cd( _trainFilesDir ) )
		throw "Directory not found!";
	
	currentDir.setNameFilters( QStringList( "*.bmp" ) );
	QStringList files = currentDir.entryList();
	for ( int i = 0; i < files.size(); i++ )
	{
		files[i] = currentDir.absoluteFilePath( files[i] );
	}

	return files;
}


/*----------------------------------------------------------------------------*/


CImage* ImageLoader::CreateImageFromBmp( QString& _fileName )
{
	QImage bmp( _fileName );
	//* 'a' symbol in unicode has value '1072', so if we get 'a' symbol, */
	//* active output is: 1072 - 1072 = 0, and so on   */	
	int activeOutput = _fileName.section( '/', -1 )[0].unicode() - 1072;

	return CreateImageFromBmp( bmp, activeOutput );
}


/*----------------------------------------------------------------------------*/


CImage* ImageLoader::CreateImageFromBmp( QImage& _image, int _activeOutput )
{
	FloatV data;
	for ( int i = 0; i < _image.height(); i++ )
	{		
		for ( int j = 0; j < _image.width(); j++ )
		{
			int pixBright = GetPixelGreyBright( _image, i, j );
			if ( pixBright > 25 )
				data.push_back( 1.0 );
			else
				data.push_back( -1.0 );
		}
	}		
	return new CImage( data, _activeOutput );
}


/*----------------------------------------------------------------------------*/


ImageV& ImageLoader::GetImages()
{
	return m_imageArray;
}


/*----------------------------------------------------------------------------*/


int ImageLoader::GetPixelGreyBright( QImage& _image, int _i, int _j )
{
	return ( abs( qGray( _image.pixel( _j, _i ) ) - 255 ) );	
}


/*----------------------------------------------------------------------------*/

